package com.ilearn.limiter.intercepter;

import com.google.common.util.concurrent.RateLimiter;
import com.ilearn.limiter.enums.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;

/**
 * @author: lyndon
 * @version: 1.0
 * @date: 2019/3/19
 */

@Slf4j
public class RateLimitInterceptor extends AbstractInterceptor {


    private RateLimitInterceptor(){
        super();
    }

    private volatile static RateLimitInterceptor instance = null;

    public static RateLimitInterceptor getInstance() {
        if (instance == null) {
            synchronized (RateLimitInterceptor.class) {
                if (instance == null) {
                    instance = new RateLimitInterceptor();
                }
            }
        }
        return instance;
    }
    /**
     * 单机全局限流器(限制QPS为requestLimitCount值)
     */
    private RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    protected ResponseEnum preFilter(HttpServletRequest request) {
        if (!rateLimiter.tryAcquire()) {
            log.info("限流中......");
            return ResponseEnum.RATE_LIMIT;
        }
        log.info("请求成功");
        return ResponseEnum.OK;
    }
}
